package com.cqhz.quwan.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.Html
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import com.blankj.utilcode.util.ConvertUtils.dp2px
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.FootballSelectedContract
import com.cqhz.quwan.mvp.FootballSelectedPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.ui.activity.BasketballSelectedActivity.Companion.REQUEST_BONUS_OPTIMIZATION
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.interfaces.SelectBallChangeListener
import com.cqhz.quwan.ui.interfaces.SelectSeriesChangeListener
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.mine.ExpertCertificationActivity
import com.cqhz.quwan.ui.widget.GridSpacingItemDecoration
import com.cqhz.quwan.ui.widget.LoadMoreDoneView
import com.cqhz.quwan.util.*
import kotlinx.android.synthetic.main.activity_football_selected.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 竞猜足彩投注选择页面
 * Created by Guojing on 2018/11/19.
 */
class FootballSelectedActivity : GoBackActivity(), AlipayContract.View, FootballSelectedContract.View, HasDaggerInject<ActivityInject>, SelectBallChangeListener, PayEventSubscribe, SelectSeriesChangeListener {

    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    @Inject
    lateinit var footballSelectedPresenter: FootballSelectedPresenter
    private var loginBean: LoginBean? = null
    private var mSelectList = ArrayList<BallMatchBean>()
    private lateinit var mSelectListAdapter: BaseQuickAdapter<*, *>
    private lateinit var mSelectChangeBean: BallMatchBean
    private var mPagePosition: Int = 0

    // 串法的两个列表
    private lateinit var mSeriesListAdapter: BaseQuickAdapter<*, *>
    private lateinit var mSeriesMoreListAdapter: BaseQuickAdapter<*, *>
    private var mSeriesList = ArrayList<BallBunch>()
    private var mSeriesMoreList = ArrayList<BallBunch>()
    private var mSelectSeriesBean: BallBunch? = null
    private var mType: Int = 0// 0上面默认显示的列表 1更多列表
    private var mAdapterPosition: Int = 0

    // 投注需要上传的参数
    private var betTimes: Int = 10// 投注倍数
    private var payAmount: Int = 0// 投注趣豆额
    private var betNum: Int = 0//
    private var betBunch: String = ""

    // 跟单需要上传的四个参数
    private var expertInfoBean: ExpertInfoBean? = null
    private var isNeedExpertAuth: Boolean = true// 是否需要专家认证：默认需要
    private var isPublishFollow = "0"// 是否发布跟单 0：是 1：否
    private var secrecySet = "0"// 保密设置 0：开赛后公开 1：开奖后公开 2：保密
    private var commissionRate = "10"// 佣金比例
    private var heelMultiple = "1"// 起更倍数

    private val mHandler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                MSG_UPDATE_UI_SELECT -> {
                    // 比对数据，更新列表和适配器
                    if (mSelectChangeBean.selectedNumber > 0) {
                        mSelectList[mSelectChangeBean.adapterPosition] = mSelectChangeBean
                    } else {
                        mSelectList.remove(mSelectList[mSelectChangeBean.adapterPosition])
                    }
                    mSelectListAdapter.notifyDataSetChanged()
                    onDataChange()
                }
                MSG_UPDATE_SERIES_SELECT -> {
                    when (mType) {
                        0 -> {
                            mSeriesList[mAdapterPosition] = mSelectSeriesBean!!
                            mSeriesListAdapter.notifyDataSetChanged()

                            if (mSeriesMoreList.size > 0) {
                                for (i in 0 until mSeriesMoreList.size) {
                                    mSeriesMoreList[i].selected = false
                                }
                                mSeriesMoreListAdapter.notifyDataSetChanged()
                            }
                        }
                        1 -> {
                            for (i in 0 until mSeriesList.size) {
                                mSeriesList[i].selected = false
                            }
                            mSeriesListAdapter.notifyDataSetChanged()

                            for (i in 0 until mSeriesMoreList.size) {
                                mSeriesMoreList[i].selected = mAdapterPosition == i
                            }
                            mSeriesMoreListAdapter.notifyDataSetChanged()
                        }
                    }
                    onDataChange()
                }
                MSG_UPDATE_UI_BACK -> {
                    if (mSelectChangeBean.selectedNumber > 0) {
                        mSelectList[mSelectChangeBean.adapterPosition] = mSelectChangeBean
                    } else {
                        mSelectList.remove(mSelectList[mSelectChangeBean.adapterPosition])
                    }
                    mSelectListAdapter.notifyDataSetChanged()
                    onDataChange()
                }
                else -> {
                }
            }
        }
    }

    companion object {
        const val REQUEST_SELECT_LOTTERY = 0x1001
        const val REQUEST_GO_TO_EXPERT = 0x1002
        const val REQUEST_BONUS_OPTIMIZATION = 0x1003
        const val MSG_UPDATE_UI_SELECT = 0x10001
        const val MSG_UPDATE_UI_BACK = 0x10002
        const val MSG_UPDATE_SERIES_SELECT = 0x10003
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun layout(): Int {
        return R.layout.activity_football_selected
    }

    override fun initView() {
        alipayPresenter.attachView(this)
        footballSelectedPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            footballSelectedPresenter.getExpertInfo(loginBean!!.userId!!)
        }

        setTitleBarText(intent.getStringExtra(KeyContract.Title))

        // 点击事件
        setOnClick()

        initAdapter()

        initData()

        setFollowOrderView()
    }

    private fun initAdapter() {
        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, rv_content.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        mPagePosition = intent.getIntExtra(KeyContract.Position, 0)
        when (mPagePosition) {
            0 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedHHListAdapter(mSelectList)
            1 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedHHListAdapter(mSelectList)
            2 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedSPFListAdapter(mSelectList, this, false)
            3 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedSPFListAdapter(mSelectList, this, true)
            4 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedZJQSListAdapter(this, mSelectList, this)
            5 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedHHListAdapter(mSelectList)
            6 -> mSelectListAdapter = CommonAdapterHelper.getFootballSelectedBQCListAdapter(mSelectList, this)
        }

        mSelectListAdapter.emptyView = emptyView
        mSelectListAdapter.setLoadMoreView(LoadMoreDoneView())

        // 当前页面列表适配器的事件
        rv_content.layoutManager = LinearLayoutManager(this)
        rv_content.adapter = mSelectListAdapter
        mSelectListAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mSelectListAdapter.getItem(position) as BallMatchBean
            item.adapterPosition = position
            when (view.id) {
                R.id.action_remove -> {
                    mSelectList.remove(item)
                    mSelectListAdapter.notifyDataSetChanged()
                    onDataChange()
                }
                R.id.action_goto_expand -> {
                    gotoFootballSelectActivity(item)
                }
            }
        }
    }

    private fun initData() {
        mSelectList.addAll(intent.getParcelableArrayListExtra(KeyContract.List))
        mSelectListAdapter.notifyDataSetChanged()

        val betNumList = ArrayList<BetNumBean>()
        for (i in 0 until mSelectList.size) {
            if (mSelectList[i].selectedNumber > 0) {
                var selected = LinkedHashSet<Int>()
                for (j in 0 until mSelectList[i].selected!!.size) {
                    if (mSelectList[i].selected!![j] == true) {
                        selected.add(j)
                    }
                }
                betNumList.add(BetNumBean(mSelectList[i].oddsMap, selected))
            }
        }
        val tempBetNumList = arrayOfNulls<Array<Any>>(betNumList.size)
        for (i in 0 until betNumList.size) {
            tempBetNumList[i] = betNumList[i].selected!!.toArray()
        }
        var bunchList = FootBallBetUtils.getBallBunch(mSelectList.size, getPlayType(), tempBetNumList, mPagePosition == 1)
        mSeriesList = bunchList[1] as ArrayList<BallBunch>
        mSeriesMoreList = bunchList[2] as ArrayList<BallBunch>
        action_expand_more.visibility = if (mSeriesMoreList.isNotEmpty()) View.VISIBLE else View.GONE


        // 初始化串法列表
        mSeriesListAdapter = CommonAdapterHelper.getFootballSeriesListAdapter(0, mSeriesList, this)
        rv_bunch.layoutManager = GridLayoutManager(this, 4)
        rv_bunch.addItemDecoration(GridSpacingItemDecoration(4, dp2px(10f), false))
        rv_bunch.adapter = mSeriesListAdapter
        mSeriesMoreListAdapter = CommonAdapterHelper.getFootballSeriesListAdapter(1, mSeriesMoreList, this)
        rv_bunch_more.layoutManager = GridLayoutManager(this, 4)
        rv_bunch_more.addItemDecoration(GridSpacingItemDecoration(4, dp2px(10f), false))
        rv_bunch_more.adapter = mSeriesMoreListAdapter

        onDataChange()
    }

    /**
     * 获取玩法类型
     * @describe 玩法
     * @return   1：胜平负；2：让球胜平负；3：比分；4：总进球；5：半全场；6：混合投注；7：单关固定；
     */
    private fun getPlayType(): Int {
        return when (mPagePosition) {
            0 -> 6
            1 -> 7
            2, 3, 6 -> mPagePosition - 1
            4 -> mPagePosition
            5 -> 3
            else -> 6
        }
    }

    /**
     * 当选中状态改变时
     */
    private fun onDataChange() {
        if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
            payAmount = 0
            tv_select_match.text = Html.fromHtml("${"投注方式".htmlFontColor("#333333")}${"（必选）".htmlFontColor("#d60000")}")
            tv_total_number.text = "${0}注${et_bunch_number.text.toString().trim()}倍 共${0}趣豆"
            tv_total_amount.text = "预计奖金 ${0.00}"
            nsv_content.visibility = View.GONE
            return
        }
        // 串法列表
        val betNumList = ArrayList<BetNumBean>()
        for (i in 0 until mSelectList.size) {
            if (mSelectList[i].selectedNumber > 0) {
                var selected = LinkedHashSet<Int>()
                for (j in 0 until mSelectList[i].selected!!.size) {
                    if (mSelectList[i].selected!![j] == true) {
                        selected.add(j)
                    }
                }
                betNumList.add(BetNumBean(mSelectList[i].oddsMap, selected))
            }
        }
        val tempBetNumList = arrayOfNulls<Array<Any>>(betNumList.size)
        val tempBetNumList2 = ArrayList<Array<Double>>(betNumList.size)
        for (i in 0 until betNumList.size) {
            tempBetNumList[i] = betNumList[i].selected!!.toArray()
            val d = FootBallBetUtils.getMinMaxOdds2(betNumList[i].selected!!.toTypedArray(), betNumList[i].oddsMap!!)
            tempBetNumList2.add(d)
        }

        var bunchList = FootBallBetUtils.getBallBunch(mSelectList.size, getPlayType(), tempBetNumList, mPagePosition == 1)
        mSeriesList = bunchList[1] as ArrayList<BallBunch>
        mSeriesMoreList = bunchList[2] as ArrayList<BallBunch>
        if (mType == 0 && mSelectSeriesBean != null && mAdapterPosition < mSeriesList.size) {
            mSeriesList[mAdapterPosition] = mSelectSeriesBean!!
        }

        action_expand_more.visibility = if (mSeriesMoreList.isNotEmpty()) View.VISIBLE else View.GONE
        if (mSeriesListAdapter != null) {
            mSeriesListAdapter.notifyDataSetChanged()
        }
        if (mSeriesMoreListAdapter != null) {
            mSeriesMoreListAdapter.notifyDataSetChanged()
        }

        // 串法提交订单的数据
        var bunchStr = ""// 选中的串法
        val betBunchs = HashSet<String>()
        for (i in 0 until mSeriesList.size) {
            if (mSeriesList[i].selected) {
                bunchStr += if (bunchStr.isEmpty()) mSeriesList[i].code else "," + mSeriesList[i].code
                betBunchs.add(mSeriesList[i].code)
            }
        }
        if (mSeriesMoreList.isNotEmpty()) {
            for (i in 0 until mSeriesMoreList.size) {
                if (mSeriesMoreList[i].selected) {
                    bunchStr += if (bunchStr.isEmpty()) mSeriesMoreList[i].code else "," + mSeriesMoreList[i].code
                    betBunchs.add(mSeriesMoreList[i].code)
                }
            }
        }

        betNum = FootBallBetUtils.betNum(betBunchs.toTypedArray(), tempBetNumList)
        payAmount = betNum * 2 * betTimes * 100// 趣豆x100
        betBunch = bunchStr

        val minVal = FootBallBetUtils.betMinVal(betBunchs.toTypedArray(), tempBetNumList2)
        val maxVal = FootBallBetUtils.betMaxVal(betBunchs.toTypedArray(), tempBetNumList2)
        val numText = "${betNum}注${betTimes}倍 共${payAmount}趣豆"
        val moneyText = "预计奖金 ${(minVal * betTimes * 100).format()}~${(maxVal * betTimes * 100).format()}"

        tv_select_match.text = if (betBunch.isNotEmpty()) betBunch.replace("-", "串") else Html.fromHtml("${"投注方式".htmlFontColor("#333333")}${"（必选）".htmlFontColor("#d60000")}")
        tv_bunch_tips.text = if (betBunch.isNotEmpty()) betBunch.replace("-", "串") + "：" + "猜中" + FootBallBetUtils.bunchNum(betBunchs.toTypedArray()) + "场可中奖" else "投注方式(必选)"
        tv_total_number.text = numText
        tv_total_amount.text = moneyText
    }

    private fun setOnClick() {
        setTitleBarRightText("奖金优化") {
            if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
                showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return@setTitleBarRightText
            }

            if (TextUtils.isEmpty(betBunch)) {
                showToast("请选择投注方式")
                return@setTitleBarRightText
            }

            if (!betBunch.contains("-1")) {
                showToast("该玩法不支持奖金优化")
                return@setTitleBarRightText
            }

            var intent = Intent(this, BonusOptimizationFootballActivity::class.java)
            intent.putExtra(KeyContract.Position, mPagePosition)
            intent.putExtra(KeyContract.PlayType, getPlayType().toString())
            intent.putExtra(KeyContract.Money, payAmount.toString())
            intent.putExtra(KeyContract.String, betBunch)
            intent.putParcelableArrayListExtra(KeyContract.List, mSelectList)
            startActivityForResult(intent, REQUEST_BONUS_OPTIMIZATION)
        }

        action_add_back.setOnClickListener {
            // 将当前页面的数据打包并跳转到列表页，并关闭当前页面
            if (mSelectList.isEmpty()) {
                finishActivity()
                return@setOnClickListener
            }
            var intent = Intent()
            intent.putExtra(KeyContract.Position, mPagePosition)
            intent.putExtra(KeyContract.Type, "0")
            intent.putParcelableArrayListExtra(KeyContract.List, mSelectList)
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
        action_expand_series.setOnClickListener {
            if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
                showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return@setOnClickListener
            }
            nsv_content.visibility = if (nsv_content.visibility == View.VISIBLE) View.GONE else View.VISIBLE
        }
        action_expand_more.setOnClickListener {
            rv_bunch_more.visibility = if (rv_bunch_more.visibility == View.VISIBLE) View.GONE else View.VISIBLE
            iv_more_drop.setImageResource(if (rv_bunch_more.visibility == View.VISIBLE) R.drawable.soccer_ic_up else R.drawable.soccer_ic_down)
        }
        action_clear.setOnClickListener {
            createDialog(title = "清空提示",
                    msg = "确认清空所有选择的比赛",
                    pos = "确认", neg = "取消",
                    ok = { _, _ ->
                        mSelectList.clear()
                        mSelectListAdapter.notifyDataSetChanged()
                        onDataChange()
                    },
                    no = { _, _ -> }).show()
        }
        action_minus.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
                showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return@setOnClickListener
            }
            if (betTimes > 1) {
                betTimes -= 1
                et_bunch_number.setText("$betTimes")
            }
            onDataChange()
        }
        action_add.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
                showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return@setOnClickListener
            }
            betTimes += 1
            et_bunch_number.setText("$betTimes")
            onDataChange()
        }
        action_goto_pay.setOnClickListener {
            commitOrder()
        }

        et_bunch_number.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (mSelectList.size < (if (mPagePosition == 1) 1 else 2)) {
                    showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                    return
                }
                try {
                    var value = s?.toString()?.toInt() ?: 0
                    betTimes = s?.toString()?.toInt() ?: 0
                    if (value == 0) {
                        betTimes = 10
                        et_bunch_number.setText("10")
                    }
                } catch (e: NumberFormatException) {
                    betTimes = 10
                }

                onDataChange()
            }

        })
        et_bunch_number.setOnEditorActionListener { view: View?, i: Int?, event: KeyEvent? ->
            when (i) {
                EditorInfo.IME_ACTION_DONE -> {
                    et_bunch_number.clearFocus()
                    KeyboardUtils.hideSoftInput(this)
                }
            }
            false
        }
    }

    /**
     * 提交订单
     */
    private fun commitOrder() {
        if (betNum == 0) {
            showToast("请选择投注方式")
            return
        }

        when {
            payAmount == 0 -> {
                showToast(if (mPagePosition == 1) "请至少选择一场比赛" else "请至少选择两场比赛")
                return
            }
            loginBean == null -> {
                toIntent(LoginActivity::class.java)
                return
            }
        }

        val args = HashMap<String, String>()
        args["userId"] = loginBean!!.userId ?: ""
        args["lotteryId"] = "21"
        args["period"] = "11"
        args["buyWay"] = "0"
        args["payAmount"] = payAmount.toString()
        args["betNum"] = betNum.toString()
        args["betTimes"] = betTimes.toString()
        args["betBunch"] = betBunch

        val betOrders = ArrayList<BetOrder>()
        for (i in 0 until mSelectList.size) {
            if (mSelectList[i].selectedNumber > 0) {
                var redNum = ""
                for (j in 0 until mSelectList[i].selected!!.size) {
                    if (mSelectList[i].selected!![j] == true) {
                        redNum += if (redNum.isEmpty()) j.toString() else ",$j"
                    }
                }
                betOrders.add(BetOrder(mSelectList[i].code, redNum, getPlayType()))
            }
        }

        args["orderBetJson"] = betOrders.json()

        if (isPublishFollow == "0") {
            if (isNeedExpertAuth) {
                createDialog(title = "温馨提示",
                        msg = "您需要认证专家后才能发布跟单",
                        pos = "去认证专家", neg = "取消",
                        ok = { _, _ ->
                            var intent = Intent(this, ExpertCertificationActivity::class.java)
                            startActivityForResult(intent, REQUEST_GO_TO_EXPERT)
                        },
                        no = { _, _ -> confirmOrder(args) }).show()
            } else {
                var rate = et_commission.text.toString().trim()
                var times = et_times.text.toString().trim()
                commissionRate = if (rate.isEmpty()) "0" else rate
                heelMultiple = if (times.isEmpty()) "1" else times

                args["isPublishFollow"] = isPublishFollow
                args["secrecySet"] = secrecySet
                args["commissionRate"] = commissionRate
                args["heelMultiple"] = heelMultiple
                confirmOrder(args)
            }
        } else {
            confirmOrder(args)
        }
    }

    /**
     *  提交订单
     */
    private fun confirmOrder(args: HashMap<String, String>) {
        action_goto_pay.isEnabled = false
        footballSelectedPresenter.postOrder(args)
    }

    /**
     * 选择或取消
     * @param  bean
     */
    override fun onItemSelectChange(bean: BallMatchBean) {
        mSelectChangeBean = bean
        mHandler.sendEmptyMessage(MSG_UPDATE_UI_SELECT)
    }

    /**
     * 选择或取消
     * @param  type            0上面默认显示的列表 1更多列表
     * @param  adapterPosition
     * @param  bean
     */
    override fun onItemSelectChange(type: Int, adapterPosition: Int, bean: BallBunch) {
        mType = type
        mAdapterPosition = adapterPosition
        mSelectSeriesBean = bean
        mHandler.sendEmptyMessage(MSG_UPDATE_SERIES_SELECT)
    }

    /**
     * 跳转到选择属性
     * @param bean
     */
    private fun gotoFootballSelectActivity(bean: BallMatchBean) {
        val intent = Intent(this, if (mPagePosition != 5) FootballSelectHHActivity::class.java else FootballSelectBFActivity::class.java)
        intent.putExtra(KeyContract.Bean, bean)
        startActivityForResult(intent, REQUEST_SELECT_LOTTERY)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    /**
     * 设置跟单
     */
    private fun setFollowOrderView() {
        // 弹出提示对话框
        action_show_dialog.setOnClickListener {
            AlertDialog.Builder(context())
                    .setMessage("1、赚佣金 是指跟单用户中奖后按照抽佣比例打赏给推单用户的金额，方案派奖时将自动派发方案推荐人佣金。\n\n2、抽佣金额 =（方案奖金-投注本金）* 佣金比例。")
                    .setPositiveButton("我知道了") { dialog, _ ->
                        dialog.dismiss()
                    }.setCancelable(true)
                    .create().show()
        }
        // 展开动画
        action_expand_follow.setOnClickListener {
            if (ll_show.visibility == View.GONE) {
                animateOpen(ll_show)
                animationIvOpen()
            } else {
                animateClose(ll_show)
                animationIvClose()
            }
        }
        et_commission.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                val value = s.toString().trim { it <= ' ' }
                et_commission.removeTextChangedListener(this)
                if (!StringUtils.isEmpty(value)) {
                    val rate = java.lang.Double.valueOf(value)
                    if (rate > if (expertInfoBean != null) expertInfoBean!!.max.toDouble() else 10.00) {
                        et_commission.setText("10")
                    }
                }
                et_commission.addTextChangedListener(this)
            }
        })
        et_times.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                val value = s.toString().trim { it <= ' ' }
                et_times.removeTextChangedListener(this)
                if (!StringUtils.isEmpty(value)) {
                    val rate = java.lang.Double.valueOf(value)
                    if (rate <= 0) {
                        et_times.setText("1")
                    }
                }
                et_times.addTextChangedListener(this)
            }
        })
        // 绑定监听事件
        iv_checked.setOnClickListener {
            if (isPublishFollow == "0") {
                isPublishFollow = "1"
                iv_checked.setImageResource(R.drawable.gd_ic_default)
            } else {
                isPublishFollow = "0"
                iv_checked.setImageResource(R.drawable.gd_ic_selected)
            }
        }
        rg_select_keep_setting.setOnCheckedChangeListener { _, checkedId ->
            secrecySet = when (checkedId) {
                R.id.action_select_after_match -> "0"
                R.id.action_select_after_prize -> "1"
                R.id.action_select_keep_secret -> "2"
                else -> "0"
            }
        }
    }

    override fun setExpertInfo(bean: ExpertInfoBean) {
        if (bean?.rank != null) {
            expertInfoBean = bean
            isNeedExpertAuth = bean.rank!! < 1
            secrecySet = if (bean.type == 1) "1" else "0"
            commissionRate = if (expertInfoBean!!.max == 0) "0" else expertInfoBean!!.max.toString()
            heelMultiple = if (expertInfoBean!!.remark == "" || expertInfoBean!!.remark == "0") "1" else expertInfoBean!!.remark
            rg_select_keep_setting.check(if (bean.type == 1) R.id.action_select_after_prize else R.id.action_select_after_match)
            et_commission.isEnabled = expertInfoBean!!.max > 0
            et_commission.setText(commissionRate)
            et_times.setText(heelMultiple)
        } else {
            isNeedExpertAuth = true
        }
    }

    override fun toPay(orderResp: OrderResp) {
        val intent = Intent(this, GoPaymentActivity::class.java)
        intent.putExtra(KeyContract.Amount, orderResp.payAmount?.toDouble())
        intent.putExtra(KeyContract.ActualAmount, orderResp.payAmount?.toDouble())
        intent.putExtra(KeyContract.LotteryName, when (mPagePosition) {
            0 -> "竞猜足球-混合投注"
            1 -> "竞猜足球-单关固定"
            2 -> "竞猜足球-胜平负"
            3 -> "竞猜足球-让球胜平负"
            4 -> "竞猜足球-总进球数"
            5 -> "竞猜足球-比分"
            6 -> "竞猜足球-半全场"
            else -> "其他"
        })
        intent.putExtra(KeyContract.OrderId, orderResp.id)
        startActivity(intent)
        finishActivity()
    }

    override fun setCommitEnable() {
        action_goto_pay.isEnabled = true
    }

    /****************************************展开动画 start****************************************/
    private fun animateOpen(view: View) {
        view.visibility = View.VISIBLE
        val animator = createDropAnimator(view, 0, action_expand_follow.height * 2 + 1)
        animator.start()

    }

    private fun animateClose(view: View) {
        val origHeight = view.height
        val animator = createDropAnimator(view, origHeight, 0)
        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                view.visibility = View.GONE
            }
        })
        animator.start()
    }

    private fun animationIvOpen() {
        val animation = RotateAnimation(0f, 180f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f)
        animation.fillAfter = true
        animation.duration = 100
        iv_expand.startAnimation(animation)
    }

    private fun animationIvClose() {
        val animation = RotateAnimation(180f, 0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f)
        animation.fillAfter = true
        animation.duration = 100
        iv_expand.startAnimation(animation)
    }

    private fun createDropAnimator(v: View, start: Int, end: Int): ValueAnimator {
        val animator = ValueAnimator.ofInt(start, end)
        animator.addUpdateListener { arg0 ->
            val value = arg0.animatedValue as Int
            val layoutParams = v.layoutParams
            layoutParams.height = value
            v.layoutParams = layoutParams
        }
        return animator
    }

    /****************************************展开动画 end****************************************/


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) when (requestCode) {
            REQUEST_SELECT_LOTTERY -> {
                // 刷新适配器
                if (data != null) {
                    mSelectChangeBean = data.getParcelableExtra<BallMatchBean>(KeyContract.Bean)
                }
                if (mSelectChangeBean != null) {
                    mHandler.sendEmptyMessage(MSG_UPDATE_UI_BACK)
                }
            }
            REQUEST_GO_TO_EXPERT -> {
                if (APP.get()!!.loginInfo != null) {
                    loginBean = APP.get()!!.loginInfo
                    footballSelectedPresenter.getExpertInfo(loginBean!!.userId!!)
                }
            }
            REQUEST_BONUS_OPTIMIZATION -> {
                finishActivity()
            }
        }
    }

    override fun onTitleBarLeftClick() {
        if (mSelectList.isEmpty()) {
            finishActivity()
            return
        }
        createDialog(title = "退出提示",
                msg = "返回将清空所有已选的号码",
                pos = "确认", neg = "取消",
                ok = { _, _ -> finishActivity() },
                no = { _, _ -> }).show()
    }

    private fun finishActivity() {
        var intent = Intent()
        intent.putExtra(KeyContract.Type, "1")
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mSelectList.isEmpty()) {
                finishActivity()
                return true
            }
            createDialog(title = "退出提示",
                    msg = "返回将清空所有已选的号码",
                    pos = "确认", neg = "取消",
                    ok = { _, _ -> finishActivity() },
                    no = { _, _ -> }).show()
        }
        return true
    }

    /**
     *
     * 创建弹出框
     */
    private fun createDialog(title: String = "", msg: String = "", pos: String = "", neg: String = "", ok: (DialogInterface, Int) -> Unit, no: (DialogInterface, Int) -> Unit): AlertDialog {
        return AlertDialog.Builder(this)
                .setTitle(title).setMessage(msg)
                .setPositiveButton(pos, ok)
                .setNegativeButton(neg, no).create()
    }

    /**
     * 绑定支付宝
     */
    override fun bindAlipay() {
        createDialog(title = "温馨提示",
                msg = "为了账户安全，请绑定支付宝",
                pos = "确认", neg = "取消",
                ok = { _, _ -> alipayPresenter.auth4alipay() },
                no = { _, _ -> }).show()
    }

    override fun doPayFinish() {
        finishActivity()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        footballSelectedPresenter.bindAlipay(APP.get()!!.loginInfo!!.userId!!, authData)
    }

    override fun onResume() {
        super.onResume()
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        alipayPresenter.detachView()
        footballSelectedPresenter.detachView()
        PayEventObserver.unregister(this)
    }
}
